package com.ruoyi.web.controller.environment;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.DeviceReqDTO;
import com.ruoyi.system.domain.TransmitterDevice;
import com.ruoyi.system.service.ISysTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
public class AirconditionerController {

    private static String prefix = "http://150.158.123.33:38080";
    private static String apiUrl = "http://150.158.123.33:38080/login";
    private static String username = "admin";
    private static String password = "BJGZJGY607";

    @Autowired
    private ISysTokenService sysTokenService;

    @PostMapping("/airconditioner/device/transmitter/logs")
    public Object getDeviceLogs(@RequestBody DeviceReqDTO device) {
        // 构建请求URL
        String url = prefix + "/device/detail/logs";
        //String param = "storeId=1&deviceTypeCode=02&deviceAddrCode=01&termId=1";
        String param = "storeId=" + (device.getStoreId() != null ? device.getStoreId() : "") +
                "&deviceTypeCode=" + (device.getDeviceTypeCode() != null ? device.getDeviceTypeCode() : "") +
                "&deviceAddrCode=" + (device.getDeviceAddrCode() != null ? device.getDeviceAddrCode() : "") +
                "&termId=" + (device.getTermId() != null ? device.getTermId() : "") +
                "&storeCode="+ (device.getStoreCode() != null ? device.getStoreCode() : "");
        // 从缓存获取token
        String token = getTokenFromCache();

        // 设置请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("token", token);

        // 发送GET请求获取数据
        String response = HttpUtils.sendGet(url, param, "UTF-8", headers);

        // 如果需要将响应中的某个字符串字段转换为int返回给前端
        // 这里假设响应中有一个字段叫做"code"，需要转换为int类型
        // 可以根据实际需求修改字段名和处理逻辑
        try {
            // 解析响应
            Object responseObject = JSON.parseObject(response);
            if (responseObject instanceof Map) {
                Map<String, Object> responseMap = (Map<String, Object>) responseObject;
                // 假设要将"code"字段转换为int
                Object codeValue = responseMap.get("code");
                if (codeValue instanceof String) {
                    int codeInt = Integer.parseInt((String) codeValue);
                    responseMap.put("code", codeInt);
                    return responseMap;
                }
            }
            return responseObject;
        } catch (Exception e) {
            // 如果转换失败，返回原始响应
            return JSON.parseObject(response);
        }
    }

    @GetMapping("/airconditioner/device/manage")
    public Object getDeviceManage() {
        // 构建请求URL
        String url = prefix + "/device/manage";
        String param = "deviceTypeCode=02&storeId=1";

        // 从缓存获取token
        String token = getTokenFromCache();

        // 设置请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("token", token);

        // 发送GET请求获取数据
        String response = HttpUtils.sendGet(url, param, "UTF-8", headers);

        // 如果需要将响应中的某个字符串字段转换为int返回给前端
        // 这里假设响应中有一个字段叫做"code"，需要转换为int类型
        // 可以根据实际需求修改字段名和处理逻辑
        try {
            // 解析响应
            Object responseObject = JSON.parseObject(response);
            if (responseObject instanceof Map) {
                Map<String, Object> responseMap = (Map<String, Object>) responseObject;
                // 假设要将"code"字段转换为int
                Object codeValue = responseMap.get("code");
                if (codeValue instanceof String) {
                    int codeInt = Integer.parseInt((String) codeValue);
                    responseMap.put("code", codeInt);
                    return responseMap;
                }
            }
            return responseObject;
        } catch (Exception e) {
            // 如果转换失败，返回原始响应
            return JSON.parseObject(response);
        }
    }

    @GetMapping("/airconditioner/device/detail/info")
    public Object getDeviceDetailInfo() {
        // 构建请求URL
        String url = prefix + "/device/detail/info";
        String param = "storeId=1&deviceTypeCode=02&deviceAddrCode=01&termId=1&storeCode=A";

        // 从缓存获取token
        String token = getTokenFromCache();

        // 设置请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("token", token);

        // 发送GET请求获取数据
        String response = HttpUtils.sendGet(url, param, "UTF-8", headers);

        // 如果需要将响应中的某个字符串字段转换为int返回给前端
        // 这里假设响应中有一个字段叫做"code"，需要转换为int类型
        // 可以根据实际需求修改字段名和处理逻辑
        try {
            // 解析响应
            Object responseObject = JSON.parseObject(response);
            if (responseObject instanceof Map) {
                Map<String, Object> responseMap = (Map<String, Object>) responseObject;
                // 假设要将"code"字段转换为int
                Object codeValue = responseMap.get("code");
                if (codeValue instanceof String) {
                    int codeInt = Integer.parseInt((String) codeValue);
                    responseMap.put("code", codeInt);
                    return responseMap;
                }
            }
            return responseObject;
        } catch (Exception e) {
            // 如果转换失败，返回原始响应
            return JSON.parseObject(response);
        }
    }

    @PostMapping("/airconditioner/device/detail/chart")
    public Object getDeviceDetailChart(@RequestBody DeviceReqDTO  device) {
        // 构建请求URL
        String url = prefix + "/device/detail/chart";
       // String param = "storeId=1&deviceTypeCode=02&deviceAddrCode=01&termId=1&storeCode=A";
        String param = "storeId=" + (device.getStoreId() != null ? device.getStoreId() : "") +
                "&deviceTypeCode=" + (device.getDeviceTypeCode() != null ? device.getDeviceTypeCode() : "") +
                "&deviceAddrCode=" + (device.getDeviceAddrCode() != null ? device.getDeviceAddrCode() : "") +
                "&termId=" + (device.getTermId() != null ? device.getTermId() : "") +
                "&storeCode="+ (device.getStoreCode() != null ? device.getStoreCode() : "");
        // 从缓存获取token
        String token = getTokenFromCache();

        // 设置请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("token", token);

        // 发送GET请求获取数据
        String response = HttpUtils.sendGet(url, param, "UTF-8", headers);

        // 如果需要将响应中的某个字符串字段转换为int返回给前端
        // 这里假设响应中有一个字段叫做"code"，需要转换为int类型
        // 可以根据实际需求修改字段名和处理逻辑
        try {
            // 解析响应
            Object responseObject = JSON.parseObject(response);
            if (responseObject instanceof Map) {
                Map<String, Object> responseMap = (Map<String, Object>) responseObject;
                // 假设要将"code"字段转换为int
                Object codeValue = responseMap.get("code");
                if (codeValue instanceof String) {
                    int codeInt = Integer.parseInt((String) codeValue);
                    responseMap.put("code", codeInt);
                    return responseMap;
                }
            }
            return responseObject;
        } catch (Exception e) {
            // 如果转换失败，返回原始响应
            return JSON.parseObject(response);
        }

        // 直接返回远程接口的响应内容
        // return JSON.parseObject(response);
    }

    /**
     * 从缓存获取token
     * @return token字符串
     */
    private String getTokenFromCache() {
        try {
            Map<String, Object> tokenInfo = sysTokenService.getCachedToken(username, apiUrl);
            if (tokenInfo != null && tokenInfo.get("token") != null) {
                return (String) tokenInfo.get("token");
            }
            // 如果缓存中没有token，重新获取并缓存
            tokenInfo = sysTokenService.getTokenWithCache(username, password, apiUrl);
            return (String) tokenInfo.get("token");
        } catch (Exception e) {
            // 如果获取失败，使用默认token（可以根据需要调整处理方式）
            return "VcXRinlhXTEJft64IYy/6HmUOdYlS7k/YpbPZkkifnzmi+Sp7j+HdcPum0Z7jn8RiqcwotgqK6nuZakj+IDNQQXvEK4VkzRseho3eIwN1y4dl/A7I+qWYjotwP51asSdK/pbPZEFIGi9rEQJ4/X5nhN99ZTZK59tnle0yayGhvDzXCYRaCKYGF7QaYP7y5nWCd32kUP/LNj01t8tc7bcbyxx+pa6k/ToDdHrNomoEq1iM7D1asJqaCIM/FzulC40dufHJkQvzCTi3U1NyT5jZkjhK+24Tz46USUa0XC1GZc=";
        }
    }

    @PutMapping("/airconditioner/device/manage/{id}")
    public Object getDeviceDetailChart(@PathVariable Long id, @RequestBody TransmitterDevice device) {
        // 构建请求URL
        String url = prefix + "/device/manage/"+ id;

        // 将设备对象转换为JSON字符串作为请求体
        String requestBody = JSON.toJSONString(device);

        // 从缓存获取token
        String token = getTokenFromCache();

        // 设置请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("token", token);

        // 发送PUT请求获取数据
        String response = HttpUtils.sendPut(url, requestBody, headers);

        // 如果需要将响应中的某个字符串字段转换为int返回给前端
        // 这里假设响应中有一个字段叫做"code"，需要转换为int类型
        // 可以根据实际需求修改字段名和处理逻辑
        try {
            // 解析响应
            Map<String, Object> responseObject = JSON.parseObject(response);
            if (responseObject != null) {
                // 假设要将"code"字段转换为int
                Object codeValue = responseObject.get("code");
                if (codeValue instanceof String) {
                    int codeInt = Integer.parseInt((String) codeValue);
                    responseObject.put("code", codeInt);
                    return responseObject;
                }
            }
            return responseObject;
        } catch (Exception e) {
            // 如果转换失败，返回原始响应
            return JSON.parseObject(response);
        }

        // 直接返回远程接口的响应内容
        // return JSON.parseObject(response);
    }
}
